//
//  CanBeBrrowedVC.m
//  BrushFace
//
//  Created by 樊娜娜 on 15/12/26.
//  Copyright © 2015年 Zzz. All rights reserved.
//

#import "CanBeBrrowedVC.h"
#import "ARRequestModel.h"
#import "NavHelper.h"
#import "BorrowOutConpousVC.h"
#import "PaymentMethodView.h"
#import "NoteVC.h"
#import "YuJiShouYiVC.h"
#import "FinanceReqModel.h"
#import "WeChat.h"
#import "AlertDialogHelper.h"

@interface CanBeBrrowedVC ()<BorrowOutConpousVCDelegate,TakeWordDelegate>
{
    int                             _days;
    int                             _priod;
    CGFloat                         _rate;
    CGFloat                         _money;
    CGFloat                         _hopeMoney;
    NSArray                         *_lilvArr;
    NSDictionary                    *_currentDict;
    CGFloat                         _curPopular;
    JSValue                         *_currentRuleJS;
    JSValue                         *_currentLimitJS;
    NSString                        *_conpousType;
    NSString                        *_conpousID;
    PaymentMethodView               *_payView;
    BOOL                            _useConpous;
    NSString                        *noteStr;
    FinanceReqModel                 *_reqModel;
    BOOL                            _isWeChat;
    BOOL                            _isAuto;
    CGFloat                         conpousShouyi;
}
@end

@implementation CanBeBrrowedVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self UIConfig];
    [self dataInit];
    conpousShouyi = 0;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapToPopularView)];
    self.popularUseView.userInteractionEnabled = YES;
    [self.popularUseView addGestureRecognizer:tap];
    [self.moneyTextField addTarget:self action:@selector(moneyTextFieldChanged:) forControlEvents:UIControlEventEditingChanged];
    [[ARRequestModel sharedInstance] fetchCanBorrowWithHopeId:self.hopeID andCB:^(id output) {
        _currentDict = output;
        _money = [[NSString stringWithFormat:@"%@",[output objectForKey:@"remaining"]] floatValue];
        [self.navBar setTitle:[NSString stringWithFormat:@"可出借%.2f元",_money]];
        self.sliderView.minimumValue = 1;
        self.sliderView.maximumValue = _money;
        self.sliderView.value = _money;
        
        self.moneyLabel.text = [NSString stringWithFormat:@"%.2f",_money];
        self.yuELabel.text = [NSString stringWithFormat:@"余额(元):%@",[output objectForKey:@"balance"]];
        self.otherYuELabel.text = self.yuELabel.text;
        _hopeMoney = [[NSString stringWithFormat:@"%@",[output objectForKey:@"hopeamount"]] floatValue];
        CGFloat shouyi = 0.0;
        _lilvArr = [output objectForKey:@"monthinterest"];
        for (NSString *str in _lilvArr) {
            shouyi += [str floatValue]*(_money/_hopeMoney);
            //shouyi = [[self notRounding:shouyi afterPoint:2] floatValue];
        }
        self.shouyiLabel.text = [NSString stringWithFormat:@"%.2f",shouyi];
        self.conpousLabel.text = [NSString stringWithFormat:@"%@张优惠券可用",[output objectForKey:@"coucount"]];
#pragma mark----xuxuejiao
        //添加了一个判断，有优惠券时字体为红色
        if ([[output objectForKey:@"coucount"] intValue])
            
        {
            self.conpousLabel.textColor=UIColorFromRGB(0xfe6b6b);
        }
#pragma mark----------------------------
    }];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - CustomMethods
- (void)UIConfig{
    
    [self.navBar setTitle:@"可出借500元"];
    self.navBar.backgroundColor = [UIColor clearColor];
    [self.navBar setLeftBtn:NAV_BAR_LEFT_BTN_TYPE_WHITE];
    
    [self.sliderView setThumbImage:[UIImage imageNamed:@"SlideAmount"] forState:UIControlStateNormal];
    [self.sliderView addTarget:self action:@selector(panForImage:) forControlEvents:UIControlEventValueChanged];
    self.sliderView.value = 1;
    
    self.allBorrowBtn.layer.cornerRadius = 3;
    self.allBorrowBtn.clipsToBounds = YES;
    _useConpous = NO;
#pragma mark --xuxuejiao
    //添加一段代码
    
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 20, 60, 44)];
    [rightBtn setTitle:@"协议" forState:UIControlStateNormal];
    rightBtn.titleLabel.font=[UIFont systemFontOfSize:12];
    [rightBtn addTarget:self action:@selector(gotoJiekuanXieYi) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.navBar setRightView:rightBtn];
}
- (void)gotoJiekuanXieYi{
    [NavHelper gotoBorrowHuanKuanInstructionsVC];
}
- (void)dataInit{
    noteStr = @"";
    _reqModel = [FinanceReqModel SceneModel];
    _isAuto = YES;
    
}

- (IBAction)yuJiShouYiBtnClick:(id)sender {
    NSString *isface = @"";
    if (_balanceBtn.selected == YES) {
        isface = @"1";
    }else{
        isface = @"0";
    }
    YuJiShouYiVC *vc = [[YuJiShouYiVC alloc] init];
    vc.hopeID = self.hopeID;
    if (_useConpous&&[self conpousIsable]) {
        vc.conpousId = _conpousID;
    }else{
        vc.conpousId = @"";
    }
    vc.isface = isface;
    if (_isAuto) {
        vc.amount = self.moneyLabel.text;
    }else{
        vc.amount = self.moneyTextField.text;
    }
    [vc setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark - action 

- (void)panForImage:(UISlider *)sender{
    self.moneyLabel.text = [NSString stringWithFormat:@"%.2f",sender.value];
    CGFloat shouyi = 0.0;
    for (NSString *str in _lilvArr) {
        shouyi += [str floatValue]*(sender.value/_hopeMoney);
        //shouyi = [[self notRounding:shouyi afterPoint:2] floatValue];
    }
    self.shouyiLabel.text = [NSString stringWithFormat:@"%.2f",shouyi];
    _curPopular = [self popularCalculateWithAmount:sender.value];
    
    CGFloat popular = [self popularCalculateWithAmount:sender.value]/[[NSString stringWithFormat:@"%@",[_currentDict objectForKey:@"faceupscale"]] floatValue];
    self.popularMoneyLabel.text = [NSString stringWithFormat:@"%.2f",popular];
    if (_useConpous) {
        if ([self conpousIsable]) {
            [self shouyiLabelChange];
        }else{
            self.conpousLabel.text = @"优惠券失效";
        }
    }
}
- (NSString *)notRounding:(float)price afterPoint:(int)position{
    NSDecimalNumberHandler* roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundDown scale:position raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
    NSDecimalNumber *ouncesDecimal;
    NSDecimalNumber *roundedOunces;
    
    ouncesDecimal = [[NSDecimalNumber alloc] initWithFloat:price];
    roundedOunces = [ouncesDecimal decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
    return [NSString stringWithFormat:@"%@",roundedOunces];
}

- (IBAction)shouDongInPutBtnClick:(id)sender {
    self.shouDongView.hidden = YES;
    self.huaDongView.hidden = NO;
    _isAuto = NO;
}
- (IBAction)huaDongInPutBtnClick:(id)sender {
    self.shouDongView.hidden = NO;
    self.huaDongView.hidden = YES;
    _isAuto = YES;
}
- (IBAction)couponsBtnClick:(id)sender {
    /**
     *  出借优惠券选择
     */
    BorrowOutConpousVC *vc = [[BorrowOutConpousVC alloc] init];
    vc.delegate = self;
    vc.interest = self.shouyiLabel.text;
    vc.amount = self.moneyLabel.text;
    vc.faceup = [_currentDict objectForKey:@"faceup"];
    vc.face = [NSString stringWithFormat:@"%f",_curPopular];
    if (_balanceBtn.selected == YES) {
        vc.isface = @"1";
    }else{
        vc.isface = @"0";
    }
    self.shouyiLabel.text = [NSString stringWithFormat:@"%.2f",[self.shouyiLabel.text floatValue]-conpousShouyi];
    vc.balance = [_currentDict objectForKey:@"balance"];
    vc.priod = [_currentDict objectForKey:@"priod"];
    vc.days = [_currentDict objectForKey:@"days"];
    [vc setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:vc animated:YES];

}
- (IBAction)balanceBtnClick:(UIButton *)sender {
    if (_currentDict.count>0) {
        CGFloat currentPopular = [[NSString stringWithFormat:@"%@",[_currentDict objectForKey:@"rtype"]] floatValue];
        if (currentPopular==0) {
            [AlertDialogHelper showToast:@"人气为0,无法抵扣"];
            return;
        }
    }
    if (sender.selected == YES) {
        sender.selected = NO;
        self.popularUseView.hidden = YES;
    }else{
        sender.selected = YES;
        self.popularUseView.hidden = NO;
        CGFloat popular = [self popularCalculateWithAmount:[self.moneyLabel.text floatValue]]/[[NSString stringWithFormat:@"%@",[_currentDict objectForKey:@"faceupscale"]] floatValue];
        self.popularMoneyLabel.text = [NSString stringWithFormat:@"%.2f",popular];
    }
}
- (void)tapToPopularView{
    [self balanceBtnClick:self.balanceBtn];
}
- (CGFloat)popularCalculateWithAmount:(CGFloat)amount{
    //当前人气
    CGFloat currentPopular = [[NSString stringWithFormat:@"%@",[_currentDict objectForKey:@"rtype"]] floatValue];
    //可抵扣人气
    CGFloat canDeductionPopular = amount/[[NSString stringWithFormat:@"%@",[_currentDict objectForKey:@"moneyscale"]] floatValue]*[[NSString stringWithFormat:@"%@",[_currentDict objectForKey:@"faceupscale"]] floatValue];
    //可用人气上限
    CGFloat popularLimit = [[NSString stringWithFormat:@"%@",[_currentDict objectForKey:@"faceup"]] floatValue];
    
   CGFloat a = currentPopular>canDeductionPopular?canDeductionPopular:currentPopular;
   return a>popularLimit?popularLimit:a;
}

- (void)conpousId:(NSString *)conpousID andJSCouponslimit:(NSString *)couponslimit andRuleJS:(NSString *)ruleJS andConpousType:(NSString *)conpousType{
    _useConpous = YES;
    JSContext *context = [[JSContext alloc] init];
    [context evaluateScript:couponslimit];
    _currentLimitJS = context[@"couponslimit"];
    JSContext *newcontext = [[JSContext alloc] init];
    [newcontext evaluateScript:ruleJS];
    _currentRuleJS = newcontext[@"rule"];
    _conpousType = conpousType;
    _conpousID = conpousID;
    [self shouyiLabelChange];
}
- (void)shouyiLabelChange{
    NSString *isface = @"";
    if (_balanceBtn.selected == YES) {
        isface = @"1";
    }else{
        isface = @"0";
    }
    NSInteger day = [[NSString stringWithFormat:@"%@",[_currentDict objectForKey:@"days"]] integerValue];
    NSInteger priod = [[NSString stringWithFormat:@"%@",[_currentDict objectForKey:@"priod"]] integerValue];
    
    JSValue *shouyi = [_currentRuleJS callWithArguments:@[_conpousType, [_currentDict objectForKey:@"faceup"],[NSString stringWithFormat:@"%f",_curPopular],isface,[_currentDict objectForKey:@"balance"],self.shouyiLabel.text,[_currentDict objectForKey:@"priod"],self.moneyLabel.text,[NSString stringWithFormat:@"%ld",day+priod*30]]];
    self.shouyiLabel.text = [NSString stringWithFormat:@"%.2f",[self.shouyiLabel.text floatValue]+[shouyi toDouble]/100];
    if ([self.shouyiLabel.text floatValue]<0.01) {
        self.shouyiLabel.text = @"暂无收益";
    }
    _conpousLabel.text = @"已选择一张优惠券";
    conpousShouyi = [shouyi toDouble]/100;
}
- (void)nullConpous:(NSInteger)number{
    _conpousLabel.text = [NSString stringWithFormat:@"%ld张优惠券可用",number];
    conpousShouyi = 0;
    _useConpous = NO;
    
}
- (BOOL)conpousIsable{
    NSString *isface = @"";
    if (_balanceBtn.selected == YES) {
        isface = @"1";
    }else{
        isface = @"0";
    }
    NSInteger day = [[NSString stringWithFormat:@"%@",[_currentDict objectForKey:@"days"]] integerValue];
    NSInteger priod = [[NSString stringWithFormat:@"%@",[_currentDict objectForKey:@"priod"]] integerValue];
    
    JSValue *shouyi = [_currentLimitJS callWithArguments:@[_conpousType, [_currentDict objectForKey:@"faceup"],[NSString stringWithFormat:@"%f",_curPopular],isface,[_currentDict objectForKey:@"balance"],self.shouyiLabel.text,[_currentDict objectForKey:@"priod"],self.moneyLabel.text,[NSString stringWithFormat:@"%ld",day+priod*30]]];
    if ([[shouyi toString]isEqualToString:@"null"]) {
        return YES;
    }
    return NO;
}
- (IBAction)allBorrowBtnClick:(id)sender {
    NSString *yue = [NSString stringWithFormat:@"%@",[_currentDict objectForKey:@"balance"]];
    CGFloat borrowMoney = _money>[yue floatValue]?[yue floatValue]:_money;
    self.moneyTextField.text = [NSString stringWithFormat:@"%.2f元",borrowMoney];
}

- (IBAction)sureBorrowBtnClick:(id)sender {
    if (_payView == nil) {
        _payView = [PaymentMethodView loadBundleNib];
        _payView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        [self.view addSubview:_payView];
    }else{
        _payView.hidden = NO;
    }
    CGFloat balance = [[NSString stringWithFormat:@"%@",[_currentDict objectForKey:@"balance"]] floatValue];
    CGFloat popular = 0.00;
    if (_balanceBtn.selected == YES) {
        popular = [self popularCalculateWithAmount:[self.moneyLabel.text floatValue]]/[[NSString stringWithFormat:@"%@",[_currentDict objectForKey:@"faceupscale"]] floatValue];
    }
    CGFloat borrowOutMoney;
    if (_isAuto) {
        borrowOutMoney = [self.moneyLabel.text floatValue];
    }else{
        borrowOutMoney = [self.moneyTextField.text floatValue];
    }
    
    if (balance>=borrowOutMoney-popular) {
        _payView.wechatPay.hidden = YES;
        _payView.balancePay.hidden = NO;
        _payView.balancePayMoney.text = [NSString stringWithFormat:@"%.2f",borrowOutMoney-popular];
        _payView.balanceYueLabel.text = [NSString stringWithFormat:@"余额(剩余%.2f元)",balance];
        [_payView.balanceSure addTarget:self action:@selector(balanceBorrowOut:) forControlEvents:UIControlEventTouchUpInside];
        
    }else{
        _payView.balancePay.hidden = YES;
        _payView.wechatPay.hidden = NO;
        _payView.wechatPayMoney.text = [NSString stringWithFormat:@"%.2f",borrowOutMoney-popular];
        _payView.wechatBalanceLabel.text = [NSString stringWithFormat:@"余额(剩余%.2f元)",balance];
        [_payView.wechatSure addTarget:self action:@selector(wechatBorrowOut:) forControlEvents:UIControlEventTouchUpInside];
    }
    
}
-(void)balanceBorrowOut:(UIButton *)sender{
    _payView.hidden = YES;
    _isWeChat = NO;
    [self ordersSubmitted];
}
-(void)wechatBorrowOut:(UIButton *)sender{
    _payView.hidden = YES;
    _isWeChat = YES;
    [self ordersSubmitted];
}
- (void)ordersSubmitted{
    NSString *isface;
    if (_balanceBtn.selected == YES) {
        isface = @"1";
    }else{
        isface = @"0";
    }
    NSString *conpousId;
    if (_useConpous&&[self conpousIsable]) {
        conpousId = _conpousID;
    }else{
        conpousId = @"";
    }
    NSString * borrowOutMoney;
    if (_isAuto) {
        borrowOutMoney = self.moneyLabel.text;
    }else{
        borrowOutMoney = self.moneyTextField.text;
    }
    [_reqModel hope_investHopeWithHopeID:self.hopeID andAmount:borrowOutMoney andIsFace:isface andCouponsid:conpousId andNote:noteStr andCB:^(id output) {
        if ([[NSString stringWithFormat:@"%@",[output objectForKey:@"result"]] integerValue]==1) {
            if ([[NSString stringWithFormat:@"%@",[output objectForKey:@"repayType"]] integerValue]==1) {
                [AlertDialogHelper showToast:[output objectForKey:@"errormsg"]];
                return ;
            }
            if (_isWeChat == YES) {
                if (![WXApi isWXAppInstalled]) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您尚未安装微信，请安装后重新尝试" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    [alert show];
                    return ;
                }
                [[NSUserDefaults standardUserDefaults] setObject:@"CHUJIE" forKey:@"PAY"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                [WeChat sendOrderToWeChatWithPartnerId:[output objectForKey:@"appId"] andPrepayId:[output objectForKey:@"packageStr"] andNonceStr:[output objectForKey:@"nonceSignPay"] andTimeStamp:[output objectForKey:@"timestampSignPay"] andSign:[output objectForKey:@"signatureSignPay"]];
            }else{
                [NavHelper gotoBorrowOutSuccess];
            }
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"%@",[output objectForKey:@"errormsg"]] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
    }];
}
- (IBAction)takeNoteBtnClick:(id)sender {
    NoteVC *notevc = [[NoteVC alloc] init];
    [notevc setHidesBottomBarWhenPushed:YES];
    notevc.delegate = self;
    
    [self.navigationController pushViewController:notevc animated:YES];
    
}
- (void)takeWord:(NSString *)words{
    NSLog(@"words%@",words);
    noteStr = words;
    self.takeWordBtn.selected = YES;
}
- (void)moneyTextFieldChanged:(UITextField *)textField{
    CGFloat shouyi = 0.0;
    for (NSString *str in _lilvArr) {
        shouyi += [str floatValue]*([textField.text floatValue]/_hopeMoney);
        //shouyi = [[self notRounding:shouyi afterPoint:2] floatValue];
    }
    self.shouyiLabel.text = [NSString stringWithFormat:@"%.2f",shouyi];
    _curPopular = [self popularCalculateWithAmount:[textField.text floatValue]];
    
    CGFloat popular = [self popularCalculateWithAmount:[textField.text floatValue]]/[[NSString stringWithFormat:@"%@",[_currentDict objectForKey:@"faceupscale"]] floatValue];
    self.popularMoneyLabel.text = [NSString stringWithFormat:@"%.2f",popular];
    if (_useConpous) {
        if ([self conpousIsable]) {
            [self shouyiLabelChange];
        }else{
            self.conpousLabel.text = @"优惠券失效";
        }
    }


}
@end
